import { computed, onMounted, ref } from "vue";
import { ElMessageBox } from "element-plus";
import { useListPage } from "@/composables/useListPage";
import { useDialog } from "@/composables/useDialog";
import { message } from "@/utils/message";
import templateApi, {
  type TemplateItem,
  type TemplateListParams,
  type TemplateListResult,
  type TemplatePayload,
  type TemplateChannelMap
} from "@/api/system/notify/template";

interface TemplateFilterForm {
  keyword: string;
  category: string;
  status: string | number;
  channel: string;
  type: string;
}

type TemplateFilterParams = TemplateFilterForm & {
  page: number;
  page_size: number;
};

const DEFAULT_FILTER: TemplateFilterForm = {
  keyword: "",
  category: "",
  status: "",
  channel: "",
  type: ""
};

const DEFAULT_CHANNEL_OPTIONS = ["websocket", "wechat", "sms", "email"];

const STATUS_OPTIONS = [
  { label: "全部状态", value: "" },
  { label: "启用", value: 1 },
  { label: "停用", value: 0 }
];

const CHANNEL_LABELS: Record<string, string> = {
  websocket: "WebSocket",
  wechat: "微信",
  sms: "短信",
  email: "邮箱",
  dingTalk: "钉钉",
  dingtalk: "钉钉",
  lark: "飞书",
  feishu: "飞书",
  app: "App",
  system: "系统",
  push: "推送"
};

type SubmitHandler = (payload: TemplatePayload) => Promise<void>;

const normaliseChannelsPayload = (
  channels: TemplateChannelMap,
  options: Array<string>
): TemplateChannelMap => {
  const result: TemplateChannelMap = {};
  const optionSet = new Set(options);

  Object.entries(channels ?? {}).forEach(([channel, config]) => {
    const enabled = Boolean(config?.enabled);
    const route = config?.route ?? "";
    const key = String(channel);
    result[key] = { enabled, route };
  });

  optionSet.forEach(channel => {
    if (!result[channel]) {
      result[channel] = { enabled: false, route: "" };
    }
  });

  return result;
};

export function useNotifyTemplate() {
  const { openDialog } = useDialog();
  const categories = ref<Array<string>>([]);
  const channelOptions = ref<Array<string>>([...DEFAULT_CHANNEL_OPTIONS]);

  const {
    formState: filterForm,
    pagination,
    dataList,
    loading,
    onSearch,
    resetForm,
    handlePageChange,
    handleSizeChange
  } = useListPage<TemplateFilterForm, TemplateItem, TemplateListResult>(
    {
      fetch: (params: TemplateFilterParams) =>
        templateApi.fetchList(params as TemplateListParams)
    },
    DEFAULT_FILTER,
    {},
    {
      responseAdapter: response => {
        categories.value = response.categories ?? [];
        const options =
          response.channels && response.channels.length > 0
            ? response.channels
            : DEFAULT_CHANNEL_OPTIONS;
        channelOptions.value = Array.from(new Set(options));
        return {
          list: response.list ?? [],
          total: response.total ?? 0,
          pageSize: response.pageSize ?? 10,
          currentPage: response.currentPage ?? 1
        };
      }
    }
  );

  const tableData = computed(() => dataList.value ?? []);

  const columns: TableColumnList = [
    { label: "模板名称", prop: "name", minWidth: 180, align: "left" },
    { label: "类型标识", prop: "type", minWidth: 160 },
    { label: "分类", prop: "category", minWidth: 120 },
    { label: "标题", prop: "title", minWidth: 200, align: "left" },
    {
      label: "内容",
      prop: "content",
      minWidth: 240,
      align: "left",
      slot: "content"
    },
    {
      label: "渠道",
      prop: "channels",
      minWidth: 200,
      align: "left",
      slot: "channels"
    },
    { label: "状态", prop: "status", width: 100, slot: "status" },
    { label: "更新时间", prop: "update_time", width: 180 },
    {
      label: "操作",
      prop: "operation",
      width: 220,
      fixed: "right",
      slot: "operation"
    }
  ];

  const fetchTemplates = async () => {
    await onSearch();
  };

  const handleSearch = async () => {
    filterForm.page = 1;
    await onSearch();
  };

  const handleResetFilters = async () => {
    await resetForm();
  };

  const submitWrapper =
    (fn: SubmitHandler) => async (payload: TemplatePayload) => {
      await fn({
        ...payload,
        category: payload.category || "",
        channels: normaliseChannelsPayload(
          payload.channels ?? {},
          channelOptions.value
        )
      });
      await fetchTemplates();
    };

  const openCreate = () => {
    openDialog(() => import("../components/template-form.vue"), {
      title: "新增通知模板",
      width: "720px",
      props: {
        mode: "create",
        categories: categories.value.slice(),
        channelOptions: channelOptions.value.slice(),
        onSubmit: submitWrapper(async payload => {
          await templateApi.create(payload);
          message("模板创建成功", { type: "success" });
        })
      }
    });
  };

  const openEdit = (item: TemplateItem) => {
    openDialog(() => import("../components/template-form.vue"), {
      title: `编辑模板 - ${item.name}`,
      width: "720px",
      props: {
        mode: "edit",
        template: item,
        categories: categories.value.slice(),
        channelOptions: channelOptions.value.slice(),
        onSubmit: submitWrapper(async payload => {
          await templateApi.update(item.id, payload);
          message("模板更新成功", { type: "success" });
        })
      }
    });
  };

  const handleToggleStatus = async (item: TemplateItem) => {
    const nextStatus = item.status === 1 ? 0 : 1;
    try {
      await templateApi.toggleStatus(item.id, nextStatus);
      message(`模板已${nextStatus === 1 ? "启用" : "停用"}`, {
        type: "success"
      });
      await fetchTemplates();
    } catch (error: any) {
      message(error?.message ?? "状态更新失败", { type: "error" });
    }
  };

  const handleDelete = async (item: TemplateItem) => {
    try {
      await ElMessageBox.confirm(
        `确认删除模板「${item.name}」吗？`,
        "删除确认",
        {
          type: "warning",
          confirmButtonText: "删除",
          cancelButtonText: "取消"
        }
      );
    } catch {
      return;
    }

    try {
      await templateApi.remove(item.id);
      message("模板已删除", { type: "success" });
      await fetchTemplates();
    } catch (error: any) {
      message(error?.message ?? "删除模板失败", { type: "error" });
    }
  };

  const channelLabel = (channel: string) => {
    const key = channel?.toString?.() ?? "";
    const normalised = key.toLowerCase();
    return CHANNEL_LABELS[normalised] ?? CHANNEL_LABELS[key] ?? key ?? "-";
  };

  const previewContent = (item: TemplateItem) => {
    if (!item?.content) return "-";
    return item.content.length > 120
      ? `${item.content.slice(0, 120)}…`
      : item.content;
  };

  onMounted(() => {
    fetchTemplates();
  });

  return {
    filterForm,
    categories,
    channelOptions,
    statusOptions: STATUS_OPTIONS,
    pagination,
    tableData,
    columns,
    loading,
    handleSearch,
    handleResetFilters,
    handlePageChange,
    handleSizeChange,
    openCreate,
    openEdit,
    handleToggleStatus,
    handleDelete,
    channelLabel,
    previewContent
  };
}
